package com.mc.websocketjavaandspring.spring;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * websocket 处理程序
 * @author jack3
 */
@Component
@Slf4j
public class MyWsHandler extends AbstractWebSocketHandler {

    private static Map<String, SessionBean> sessionMap;
    private static AtomicInteger clientIdMaker;

    static {
        sessionMap = new ConcurrentHashMap<>();
        clientIdMaker = new AtomicInteger(0);
    }

    // 建立链接
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        SessionBean sessionBean = new SessionBean(clientIdMaker.incrementAndGet(), session);
        sessionMap.put(session.getId(), sessionBean);
    }

    // 接收到消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info(sessionMap.get(session.getId()).getClientId()+"---message--"+message.getPayload());
    }

    // 传输异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if(session.isOpen()){
            session.close();
        }
        sessionMap.remove(session.getId());
    }

    // 关闭链接
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        sessionMap.remove(session.getId());
        log.info("关闭链接");
    }

    @Scheduled(fixedRate = 5000)
    public void sendMessage() {
        log.info("sendMessage6--------------------------------------------------------------");
        sessionMap.forEach((k, v)-> {
            try {
                v.getWebSocketSession().sendMessage(new TextMessage("hello world6676"));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
